package ads_fld

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"server/global"
	"server/model/common/request"
)

type AdsFldService struct {
}

func (adsFldService *AdsFldService) CreateAdsFld(adsFld *AdsFld) (err error) {
	err = global.SysDB.Create(adsFld).Error
	return err
}

func (adsFldService *AdsFldService) DeleteAdsFld(adsFld AdsFld) (err error) {
	err = global.SysDB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Model(&AdsFld{}).Where("id = ?", adsFld.ID).Update("deleted_by", adsFld.DeletedBy).Error; err != nil {
			return err
		}
		if err = tx.Delete(&adsFld).Error; err != nil {
			return err
		}
		return nil
	})
	return err
}

func (adsFldService *AdsFldService) DeleteAdsFldByApiId(apiId uint) (err error) {
	tx4 := global.SysDB.Unscoped().Delete(AdsFld{}, "api_id = ?", apiId)
	if tx4.Error != nil {
		errMsg := fmt.Sprintf("AdsFld删除表%d字段失败:%s", apiId, tx4.Error)
		global.Logger.Info(errMsg)
		return errors.New(errMsg)
	}
	return nil
}

func (adsFldService *AdsFldService) DeleteAdsFldByIds(ids request.IdsReq, deleted_by uint) (err error) {
	err = global.SysDB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Model(&AdsFld{}).Where("id in ?", ids.Ids).Update("deleted_by", deleted_by).Error; err != nil {
			return err
		}
		if err := tx.Where("id in ?", ids.Ids).Delete(&AdsFld{}).Error; err != nil {
			return err
		}
		return nil
	})
	return err
}

func (adsFldService *AdsFldService) UpdateAdsFld(adsFld AdsFld) (err error) {
	err = global.SysDB.Save(&adsFld).Error
	return err
}

func (adsFldService *AdsFldService) GetAdsFldById(id uint) (adsFld AdsFld, err error) {
	err = global.SysDB.Where("id = ?", id).First(&adsFld).Error
	return
}

func (adsFldService *AdsFldService) GetAdsFldInfoList(info AdsFldSearch) (list []AdsFld, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.SysDB.Model(&AdsFld{})
	var adsFlds []AdsFld
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.SrcTbName != "" {
		db = db.Where("src_tb_name = ?", info.SrcTbName)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	err = db.Limit(limit).Offset(offset).Find(&adsFlds).Error
	return adsFlds, total, err
}

func (adsFldService *AdsFldService) GetAllAdsFlds() (adsFld []AdsFld, err error) {
	err = global.SysDB.Find(&adsFld).Error
	return adsFld, err
}

func (adsFldService *AdsFldService) GetAdsFld() (adsFld []AdsFld, err error) {
	err = global.SysDB.Find(&adsFld).Error
	return adsFld, err
}
